/*
 * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.example.ventilation.code.fragment.DeviceGroup;

import android.content.DialogInterface;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.ventilation.R;
import com.example.ventilation.base.BaseMenuFragment;
import com.example.ventilation.code.adapter.DeviceWindListAdapter;
import com.example.ventilation.code.common.model.ReqEntity;
import com.example.ventilation.code.common.model.WindInfoEntity;
import com.example.ventilation.code.fragment.DataGroup.DataWindEditFragment;
import com.example.ventilation.code.fragment.DeviceGroup.Detail.Detail_Tabs_WindFragment;
import com.example.ventilation.code.utils.GsonTools;
import com.example.ventilation.code.utils.HttpNetUtils;
import com.example.ventilation.code.utils.HttpUtils.PostParams;
import com.example.ventilation.code.utils.HttpUtils.RespListener;
import com.example.ventilation.code.utils.SharePrefrenceUtil;
import com.example.ventilation.code.utils.Utils;
import com.example.ventilation.code.utils.WebSocket.WebSocketManager;
import com.example.ventilation.code.utils.WebSocket.WsManager;
import com.example.ventilation.code.utils.WebSocket.WsStatusListener;
import com.example.ventilation.code.utils.XToastUtils;
import com.github.clans.fab.FloatingActionMenu;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xuexiang.xpage.AppPageConfig;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.model.PageInfo;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.DialogLoader;
import com.xuexiang.xui.widget.statelayout.StatefulLayout;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;
import com.yanzhenjie.recyclerview.touch.OnItemStateChangedListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Response;
import okio.ByteString;

import static com.example.ventilation.code.utils.WebSocket.WsStatus.DISCONNECTED;

/**
 * 设备监测--测风装置监测
 *
 * @author mashuxing
 * @since 2022/1/18
 */

@Page(name = "测风装置监测")
public class DeviceWindFragment extends BaseMenuFragment {
    private static final String TAG = "DeviceWindFragment";
    @BindView(R.id.recyclerView)
    SwipeRecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    SharePrefrenceUtil sharePrefrenceUtil;
    @BindView(R.id.ll_stateful)
    StatefulLayout mLlStateful;
    JSONArray monitorList;
    private int clickPositon = -1;

    private DeviceWindListAdapter mAdapter;
    private int page = 1;
    private WsManager wsManager;
    @BindView(R.id.fab_menu)
    FloatingActionMenu mFloatingActionMenu;

    private int mType = Utils.TYPE_LIST;
    private JSONObject objparam;


    @Override
    protected List<PageInfo> getPageContents() {
        return AppPageConfig.getInstance().getUtils();
    }

    @Override
    protected TitleBar initTitle() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.page_device_refresh;
    }

    @Override
    protected void initViews() {
        Log.e(TAG, "initViews: ++++++=");
        
        WidgetUtils.initRecyclerView(mRecyclerView);

        //必须在setAdapter之前调用
        mRecyclerView.setOnItemMenuClickListener(mMenuItemClickListener);
        sharePrefrenceUtil = new SharePrefrenceUtil(getActivity());
        mRecyclerView.setAdapter(mAdapter = new DeviceWindListAdapter(new ArrayList<>(), mType, mRecyclerView));

        // 监听拖拽和侧滑删除，更新UI和数据源。
        mRecyclerView.setOnItemMoveListener(onItemMoveListener);
        // 监听Item的手指状态:拖拽、侧滑、松开。
        mRecyclerView.setOnItemStateChangedListener(mOnItemStateChangedListener);


        // 长按拖拽，默认关闭。
        mRecyclerView.setLongPressDragEnabled(true);
        // 滑动删除，默认关闭。
        mRecyclerView.setItemViewSwipeEnabled(false);

        //下拉刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 1;
                        getWindInfo(true, refreshLayout);
                    }
                }, 2000);
            }
        });
        //上拉加载
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getWindInfo(false, refreshLayout);
                    }
                }, 2000);
            }
        });
        mRefreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
        SharePrefrenceUtil sharePrefrenceUtil = new SharePrefrenceUtil(this.getActivity());

        wsManager = WebSocketManager.getWsManager();
        wsManager.setWsStatusListener(wsStatusListener);
        wsManager.startConnect();
        monitorList = new JSONArray();
    }

    /**
     * Item的拖拽/侧滑删除时，手指状态发生变化监听。
     */
    private OnItemStateChangedListener mOnItemStateChangedListener = new OnItemStateChangedListener() {
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            if (actionState == OnItemStateChangedListener.ACTION_STATE_DRAG) {
//                mTitleBar.setSubTitle("状态：拖拽");
            } else if (actionState == OnItemStateChangedListener.ACTION_STATE_SWIPE) {
//                mTitleBar.setSubTitle("状态：滑动删除");
            } else if (actionState == OnItemStateChangedListener.ACTION_STATE_IDLE) {
//                mTitleBar.setSubTitle("状态：手指松开");
            }
        }
    };

    /**
     * 监听拖拽和侧滑删除，更新UI和数据源。
     */
    private OnItemMoveListener onItemMoveListener = new OnItemMoveListener() {
        @Override
        public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
            return mAdapter.onMoveItem(srcHolder, targetHolder);
        }

        @Override
        public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {
            int position = mAdapter.onRemoveItem(srcHolder);
            XToastUtils.toast("现在的第" + (position + 1) + "被删除。");
        }

    };

    private WsStatusListener wsStatusListener = new WsStatusListener() {
        @Override
        public void onOpen(Response response) {
            Log.d("", "WsManager-----onOpen");
        }

        @Override
        public void onMessage(String text) {

            WindInfoEntity.MonitorObj entity = GsonTools.getVo(text, WindInfoEntity.MonitorObj.class);
            if (entity != null && entity.getSuccess() && entity.getObj() != null) {
                for (int i = 0; i < mAdapter.getItemCount(); i++) {
                    if (mAdapter.getItem(i).getnSubStationID() == entity.getObj().getId()) {
                        updataInfo(mAdapter.getItem(i), entity.getObj());
                        mAdapter.refresh(i, mAdapter.getItem(i));
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
            Log.d("", "WsManager-----onMessage");
        }

        public void updataInfo(WindInfoEntity.WindEntity entity1, WindInfoEntity.WindEntity entity2) {
            entity1.setId(entity2.getId());
            entity1.setDeviceId(entity2.getId());
            entity1.setDeviceType(entity2.getDeviceType());
            entity1.setIsRun(entity2.getIsRun());
            entity1.setV1A(entity2.getV1A());
            entity1.setV1B(entity2.getV1B());
            entity1.setV1C(entity2.getV1C());
            entity1.setV2A(entity2.getV2A());
            entity1.setV2B(entity2.getV2B());
            entity1.setV2C(entity2.getV2C());
            entity1.setV3A(entity2.getV3A());
            entity1.setV3B(entity2.getV3B());
            entity1.setV3C(entity2.getV3C());
            entity1.setVa(entity2.getVa());
            entity1.setmPa(entity2.getmPa());
            entity1.setPa(entity2.getPa());
            entity1.setmValue(entity2.getmValue());
            entity1.setSectional(entity2.getSectional());
            entity1.setM3(entity2.getM3());
            entity1.setNetStatus(entity2.getNetStatus());
            entity1.setSign(entity2.getSign());
            entity1.setMonitor(entity2.getMonitor());
            entity1.setNine(entity2.getNine());
            entity1.setUrl(entity2.getUrl());
        }

        @Override
        public void onMessage(ByteString bytes) {
            Log.d("", "WsManager-----onMessage");
        }

        @Override
        public void onReconnect() {
            Log.d("", "WsManager-----onReconnect");
        }

        @Override
        public void onClosing(int code, String reason) {
            Log.d("", "WsManager-----onClosing");
        }

        @Override
        public void onClosed(int code, String reason) {
            Log.d("", "WsManager-----onClosed");
        }

        @Override
        public void onFailure(Throwable t, Response response) {
            Log.d("", "WsManager-----onFailure");
        }
    };
    /**
     * 从item详情页面，往回返本页面时候调用
     *
     * */
    @Override
    public void onStart() {
        super.onStart();
        if (wsManager.getCurrentStatus() == DISCONNECTED){
            wsManager.startConnect();
            //TODO 重构
            objparam = new JSONObject();
            try {
                objparam.put("type", "deviceStatus");
                objparam.put("obj", monitorList);
            } catch (Exception e) {
            }
            SystemClock.sleep(500);
            wsManager.sendMessage(objparam.toString());
        }

    }

    /**
     * 不可见时候ws停止 --> 返回页面走onStart()重新启动
     */
    @Override
    public void onPause() {
        super.onPause();
        wsManager.stopConnect();
    }

    //初始化或者最下面的tab时调用
    // 显示时，重新发送websocket请求
    public void Show(boolean showflag) {
        if (showflag) {
            if (null == wsManager) return;
            wsManager.startConnect();
            wsManager.setWsStatusListener(wsStatusListener);
            objparam = new JSONObject();
            try {
                objparam.put("type", "deviceStatus");
                objparam.put("obj", monitorList);
            } catch (Exception e) {
            }
            SystemClock.sleep(500);
            wsManager.sendMessage(objparam.toString());
        } else {
            if (null != wsManager)
                wsManager.stopConnect();
        }
    }

    /**
     * 分站信息
     * @param firstpageFlag 是否第一页加载
     */
    private void getWindInfo(boolean firstpageFlag, RefreshLayout refreshLayout) {
        Log.e(TAG, "getWindInfo: ======");
        //参数设置
        final PostParams params = new PostParams();
        //登录请求参数设置
        ReqEntity.CommonReq reqobj = new ReqEntity.CommonReq();
        ReqEntity.PageInfo pageInfo = new ReqEntity.PageInfo();
        pageInfo.setRows(ReqEntity.PageRows);
        pageInfo.setPage(page);//反复增加page
        reqobj.setnGroupID(sharePrefrenceUtil.getGroupID());
        reqobj.setPageInfo(pageInfo);
        params.setReqBodyObj(reqobj);
        //登录请求
        HttpNetUtils.getWind(getActivity(), params, new RespListener(getActivity()) {
            @Override
            public void getResp(JSONObject obj) {
                //返回数据
                WindInfoEntity entity = GsonTools.getVo(obj.toString(), WindInfoEntity.class);
                //成功
                if (entity.getSuccess()) {
                    if (page == 1 && entity.getObj().getData().size() == 0) {//数据为空的情况
                        mLlStateful.showEmpty();
                        mRefreshLayout.setEnableLoadMore(false);
                        refreshLayout.finishRefresh();
                        monitorList = new JSONArray();
                    } else {
                        if (firstpageFlag) {//初次加载第一页
                            mAdapter.refresh(entity.getObj().getData());
                            refreshLayout.finishRefresh();
                            refreshLayout.resetNoMoreData();

                            monitorList = new JSONArray();
                            //把数据一次放入list中
                            for (int i = 0; i < entity.getObj().getData().size(); i++) {
                                if (entity.getObj().getData().get(i).getnSubStationID() != null)
                                    monitorList.put(entity.getObj().getData().get(i).getnSubStationID());
                            }
                        } else {//加载更多
                            //加载到底 --> 没有更多的时候的处理
                            if (entity.getObj().getData().size() == 0) {
                                XToastUtils.toast("数据全部加载完毕");
                                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                            }

                            //加载更多
                            mAdapter.loadMore(entity.getObj().getData());
                            refreshLayout.finishLoadMore();
                            for (int i = 0; i < entity.getObj().getData().size(); i++) {
                                if (entity.getObj().getData().get(i).getnSubStationID() != null)
                                    monitorList.put(entity.getObj().getData().get(i).getnSubStationID());
                            }
                        }
                        page++;
                    }
                    JSONObject objparam = new JSONObject();
                    try {
                        objparam.put("type", "deviceStatus");
                        objparam.put("obj", monitorList);
                    } catch (Exception e) {
                    }

                    wsManager.sendMessage(objparam.toString());
                } else {
                    //获取失败
                    showError();
                    XToastUtils.error("请求超时，请重新刷新页面");
                    if (firstpageFlag)
                        refreshLayout.finishRefresh();
                    else
                        refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void doFailed() {
                showOffline();
                XToastUtils.success("获取信息失败，请检查网络！");
            }
        });
    }

    private void showOffline() {
        mLlStateful.showOffline(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRefreshLayout.autoRefresh();
            }
        });
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void showError() {
        mLlStateful.showError(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRefreshLayout.autoRefresh();
            }
        });
        mRefreshLayout.setEnableLoadMore(false);
    }

    @OnClick({R.id.fab_loading, R.id.fab_empty, R.id.fab_error, R.id.fab_no_network, R.id.fab_content})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab_loading:
//                loading();
                break;
            case R.id.fab_empty:
//                mMultipleStatusView.showEmpty();
                break;
            case R.id.fab_error:
//                mMultipleStatusView.showError();
                break;
            case R.id.fab_no_network:
//                mMultipleStatusView.showNoNetwork();
                break;
            case R.id.fab_content:
//                mMultipleStatusView.showContent();
                break;
        }
        mFloatingActionMenu.toggle(false);
    }

    @Override
    protected void initListeners() {
        mAdapter.setOnItemClickListener(new RecyclerViewHolder.OnItemClickListener<WindInfoEntity.WindEntity>() {
            @Override
            public void onItemClick(View itemView, WindInfoEntity.WindEntity item, int position) {
                clickPositon = position;
                // openNewPageForResult(DataWindDetailFragment.class,"object",item,Utils.SAVECODE);
                openNewPageForResult(Detail_Tabs_WindFragment.class, "object", item, Utils.SAVECODE);
            }
        });
    }

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private OnItemMenuClickListener mMenuItemClickListener = new OnItemMenuClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge, int position) {
            menuBridge.closeMenu();

            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

            if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                clickPositon = position;
                if (menuPosition == 1)
                    openNewPageForResult(DataWindEditFragment.class, "object", mAdapter.getItem(position), Utils.SAVECODE);
                else {
                    DialogLoader.getInstance().showConfirmDialog(
                            getActivity(), "确定要删除该条记录吗？",
                            getString(R.string.lab_yes),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            },
                            getString(R.string.lab_no),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }
                    );
                }
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void changeType(Integer type) {
        mType = type;
        if (mType == Utils.TYPE_LIST) {
            WidgetUtils.initRecyclerView(mRecyclerView);
        } else {
            WidgetUtils.initGridRecyclerView(mRecyclerView, 2);
        }
        mAdapter.setItemViewType(mType);
    }
}
